from flask import request, current_app, send_from_directory, make_response
from api.models import Goods, Pictrue, GoodsAttr
from api.goods import goods_api, goods_blue
from api.utils.response import to_response
from api.utils.baseResource import BaseResource
from api import db
from api.utils.tokens import login_required
from api.utils.utils import allow_upload, md5_file


class GoodsResource(BaseResource):
    def post(self):
        try:
            attr_static = request.json.get('attr_static')
            attr_dynamic = request.json.get('attr_dynamic')
            pics = request.json.get('pics')
            name = request.json.get('name')
            price = request.json.get('price')
            number = request.json.get('number')
            weight = request.json.get('weight')
            introduce = request.json.get('introduce')
            cid_one = request.json.get('cid_one')
            cid_two = request.json.get('cid_two')
            cid_three = request.json.get('cid_three')
            good = Goods(name=name, price=price, weight=weight, cid_one=cid_one, number=number, introduce=introduce,
                         cid_two=cid_two, cid_three=cid_three)
            db.session.add(good)
            db.session.commit()
            for p in eval(pics):
                tp = Pictrue(gid=good.id, path=p)
                db.session.add(tp)
            for s in eval(attr_static):
                sta = GoodsAttr(gid=good.id, aid=int(s['id']), val=s['val'], _type='static')
                db.session.add(sta)
            for d in eval(attr_dynamic):
                if d['val']:
                    ddy = GoodsAttr(gid=good.id, aid=int(d['id']), val=d['val'], _type='dynamic')
                    db.session.add(ddy)
            db.session.commit()
            return to_response(200, msg='添加成功', data=good.to_dict())
        except Exception as e:
            print(e)
            return to_response(10020)

    def delete(self):
        goods_id = request.args.get('id')
        try:
            good = Goods.query.get(goods_id)
        except Exception as e:
            return to_response(10020)

        if not good:
            return to_response(10017)

        try:
            db.session.delete(good)
            db.session.commit()
            return to_response(200, msg='删除成功')
        except Exception as e:
            return to_response(10020)


goods_api.add_resource(GoodsResource, '/goods')


@goods_blue.route('/goods_list', methods=['GET'])
@login_required
def get_goods_list():
    name = request.args.get('name')
    try:
        if name:
            goods = Goods.query.filter(Goods.name.like('%{}%'.format(name))).all()
        else:
            goods = Goods.query.all()

        data = [good.to_dict() for good in goods]
        return to_response(200, data=data)
    except Exception as e:
        print(e)
        return to_response(10020)


@goods_blue.route('/goods_image', methods=['POST'])
@login_required
def upload_image():
    file = request.files.get('file')
    if not file:
        return to_response(10000)

    if allow_upload(file.filename):
        file_path = current_app.config['SERVER_IMG_UPLOADS']
        end_file = file.filename.split('.')[-1]
        file_name = md5_file()

        file.save(f'{file_path}/{file_name}.{end_file}')
        data = {
            'path': f'/static/img/{file_name}.{end_file}',
            'url': f'http://127.0.0.1:5000/static/img/{file_name}.{end_file}'
        }
        return to_response(200, data=data, msg='文件上传成功！')
    else:
        return to_response(10018)


@goods_blue.route('/uploads/<filename>')
@login_required
def download_file(filename):
    try:
        response = make_response(send_from_directory(current_app.config["SERVER_IMG_UPLOADS"], filename))
        return response
    except Exception as e:
        return f"文件读取异常{e}"
